package com.yc.jpyy.investig.controller;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.utils.manydatasource.HandlerDataSource;
import com.yc.jpyy.base.bean.RestResponse;
import com.yc.jpyy.base.controller.BaseController;
import com.yc.jpyy.base.util.PageBean;
import com.yc.jpyy.investig.service.InvestigService;
import com.yc.jpyy.utils.Tools;

@Controller
@RequestMapping(value = "/investig")
@Scope("prototype")
public class InvestigController extends BaseController {

	@Autowired
	private InvestigService investigService;
	private static Logger logger = LoggerFactory
			.getLogger(InvestigController.class);

	// 新增违章处理
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addinvestig", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String addinvestig(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");
		try {
			/*
			 * //获取流 InputStream is = request.getInputStream(); byte[] bytes =
			 * new byte[1024 * 1024]; int nRead = 1; int nTotalRead = 0; while
			 * (nRead > 0) { nRead = is.read(bytes, nTotalRead, bytes.length -
			 * nTotalRead); if (nRead > 0) nTotalRead = nTotalRead + nRead; }
			 * //读取的字节流转换成字符串 String investig = new String(bytes, 0, nTotalRead,
			 * "utf-8");
			 */
			String info = request.getAttribute("info").toString();
			// HandlerDataSource.setDataSource("bizDataSource");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			System.out.println("paramsMap" + paramsMap);
			investigService.addInvestigServer(paramsMap);
			logger.info("新增违章处理成功");
			response.setReturnMsg(1, "操作成功");
			return response.toJSON();

		} catch (Exception e) {
			logger.error("新增违章处理异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 删除违章处理
	@SuppressWarnings("finally")
	@RequestMapping(value = "/delinvestig", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String delinvestig(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			System.out.println("paramsMap" + paramsMap);
			String ids = paramsMap.get("ids").toString();
			String[] idarray = ids.split(",");
			paramsMap.put("idarray", idarray);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = investigService.delInvestigServer(paramsMap);
			if (ret >= 1) {
				response.setReturnMsg(1, "删除成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "删除失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("删除违章处理异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 逻辑删除违章处理
	@SuppressWarnings("finally")
	@RequestMapping(value = "/delforUpdateinvestigDao", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String delforUpdateinvestigDao(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			System.out.println("paramsMap" + paramsMap);
			String ids = paramsMap.get("ids").toString();
			String[] idarray = ids.split(",");
			paramsMap.put("idarray", idarray);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			int ret = investigService.delforUpdateInvestigServer(paramsMap);
			if (ret > 0) {
				response.setReturnMsg(1, "逻辑删除成功");
				return response.toJSON();
			} else {
				response.setReturnMsg(0, "删除失败");
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.error("删除公司异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			response.setReturnException(e.toString());
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 查询单条违章处理
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findinvestigByID", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findinvestigByID(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			Map<String, Object> val = investigService.findInvestigByIDServer(paramsMap);
			int retSize = val.size();
			if (retSize == 0) {
				response.setReturnMsg(1, "无查询数据");
				return response.toJSON();
			} else {
				response.setReturnMsg(1, "查询单条数据成功");
				response.setListData(val);
				return response.toJSON();
			}

		} catch (Exception e) {
			logger.info("查询单条数据异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("查询单条数据异常");

		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 修改违章处理
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateinvestig", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateinvestig(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse();
		request.setCharacterEncoding("UTF-8");
		try {
			/*
			 * //获取流 InputStream is = request.getInputStream(); byte[] bytes =
			 * new byte[1024 * 1024]; int nRead = 1; int nTotalRead = 0; while
			 * (nRead > 0) { nRead = is.read(bytes, nTotalRead, bytes.length -
			 * nTotalRead); if (nRead > 0) nTotalRead = nTotalRead + nRead; }
			 * //读取的字节流转换成字符串 String investig = new String(bytes, 0, nTotalRead,
			 * "utf-8");
			 */
			String info = request.getAttribute("info").toString();
			// HandlerDataSource.setDataSource("bizDataSource");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			investigService.updateInvestig(paramsMap);
			response.setReturnMsg(1, "操作成功");
			return response.toJSON();

		} catch (Exception e) {
			logger.info("修改违章处理异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnMsg("操作失败");
			e.printStackTrace();
		}

		finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}

	}

	// 查询所有违章信息（查询条件并且分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findinvestig", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findinvestig(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			PageBean pageBean = investigService.findInvestigServer(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setTotalCount(pageBean.getAllRow());
			response.setTotalPage(pageBean.getTotalPage());
			response.setListData(pageBean.getList());
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询台帐违章信息（查询条件并且分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findAccountReportinvestig", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findAccountReportinvestig(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			PageBean pageBean = investigService.findInvestigServer(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setTotalCount(pageBean.getAllRow());
			response.setTotalPage(pageBean.getTotalPage());
			response.setListData(pageBean.getList());
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	// 查询星期报表违章信息（查询条件并且分页）
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findWeeksReportinvestig", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findWeeksReportinvestig(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			System.out.println("info" + info);
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			PageBean pageBean = investigService.findInvestigServer(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setTotalCount(pageBean.getAllRow());
			response.setTotalPage(pageBean.getTotalPage());
			response.setListData(pageBean.getList());
			return response.toJSON();

		} catch (Exception e) {
			logger.error("findCompany" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	@SuppressWarnings("finally")
	@RequestMapping(value = "/findPunishment", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findPunishment(HttpServletRequest request)
			throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		request.setCharacterEncoding("UTF-8");
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			// 设置数据源
			HandlerDataSource.setDataSource(dbcode);
			List<Map<String, Object>> list = investigService.findPunishmentServer(paramsMap);
			response.setReturnMsg(1, "操作成功");
			response.setListData(list);
			return response.toJSON();
		} catch (Exception e) {
			logger.error("findPunishment" + e.toString());
			response.setReturnCode(1);
			response.setReturnMsg("查询失败");
			response.setReturnException(e.toString());
		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateInvestigScoreToDriver", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateInvestigScoreToDriver(
			HttpServletRequest request) throws UnsupportedEncodingException {

		RestResponse response = new RestResponse(Optional.ofNullable(
				request.getAttribute("pubKey")).orElse(""));
		try {
			String info = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(info);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			Map<String, Object> driverMap = investigService.findDriverIDforInvestig(paramsMap);
			int val = 0;
			if (Tools.isNotEmpty(driverMap)) {
				int driverid = Integer.parseInt(driverMap.get("id").toString());
				paramsMap.put("selectdriverid", driverid);
				logger.info("更新两条");
				val = investigService.updateInvestigScoreToDriverAll(paramsMap);
			} else {
				logger.info("更新一条");
				val = investigService.updateInvestigServer(paramsMap);
			}
			System.out.println(val);
			if (val == 1) {
				response.setReturnMsg(1, "成功");
			} else {
				response.setReturnMsg(0, "失败");
			}

			return response.toJSON();

		} catch (Exception e) {
			logger.error("异常" + e.toString());
			// 异常信息
			response.setReturnCode(0);
			response.setReturnException(e.toString());
			response.setReturnMsg("异常");

		} finally {
			HandlerDataSource.clear();
			return response.toJSON();
		}
	}

	/**
	 * 根据DriverId查询
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/getInvestigsByDriverId", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String getInvestigsByDriverId(
			HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String checkParameter = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = investigService.getInvestigsByDriverId(paramsMap);
			resultMap.put(
					"pubKey",
					Optional.ofNullable(request.getAttribute("pubKey")).orElse(
							""));
		} catch (Exception e) {
			logger.info("getInvestigsByDriverId" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}

	/**
	 * 稽查处理撤回操作
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/cancel", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String cancel(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String checkParameter = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = investigService.cancel(paramsMap);
			resultMap.put(
					"pubKey",
					Optional.ofNullable(request.getAttribute("pubKey")).orElse(
							""));
		} catch (Exception e) {
			logger.info("cancel" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "撤回失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}

	/**
	 * 更新审核状态
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/updateInvesStatus", method = { RequestMethod.GET,
			RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String updateInvesStatus(HttpServletRequest request)
			throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String checkParameter = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = investigService.updateInvesStatus(paramsMap);
			resultMap.put(
					"pubKey",
					Optional.ofNullable(request.getAttribute("pubKey")).orElse(
							""));
		} catch (Exception e) {
			logger.info("updateInvesStatus" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "更新失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}

	/**
	 * 多条件分页查询
	 * 
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 *//*
	@SuppressWarnings("finally")
	@RequestMapping(value = "/findInvestigByVariable", method = {
			RequestMethod.GET, RequestMethod.POST }, produces = "application/json; charset=utf-8")
	public @ResponseBody String findInvestigByVariable(
			HttpServletRequest request) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		Map<String, Object> resultMap = new HashMap<>();
		try {
			String checkParameter = request.getParameter("info");
			Map<String, Object> paramsMap = Tools.JsonToMap(checkParameter);
			String dbcode = paramsMap.get("dbcode").toString();
			HandlerDataSource.setDataSource(dbcode);
			resultMap = investigService.findInvestigByVariable(paramsMap);
			resultMap.put(
					"pubKey",
					Optional.ofNullable(request.getAttribute("pubKey")).orElse(
							""));
		} catch (Exception e) {
			logger.info("findInvestigByVariable" + e.toString());
			resultMap.put("returnCode", 0);
			resultMap.put("returnMsg", "查询失败");
		} finally {
			HandlerDataSource.clear();
			return JSON.toJSONString(resultMap);
		}

	}*/
}
